<style></style>
<template>
  <div>
    <i-page-header>
      <div slot="title" class="ivu-mt ivu-mb">
        <router-link :to="{ path: '/system/news/index' }">
          <Button icon="ios-arrow-back" size="small" class="mr20">返回</Button>
        </router-link>
        <span
          v-text="$route.params.id ? '编辑新闻' : '添加新闻'"
          class="mr20"
        ></span>
      </div>
    </i-page-header>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <el-form ref="news" :model="news" label-width="100px">
        <el-tabs>
          <el-tab-pane label="基本配置">
            <Col v-bind="grid">
              <el-form-item
                label="标题:"
                prop="title"
                :rules="[{ required: true, message: '请输入标题' }]"
              >
                <el-input
                  placeholder="请输入标题"
                  autocomplete="off"
                  v-model="news.title"
                ></el-input>
              </el-form-item>
            </Col>
            <Col v-bind="grid">
              <el-form-item label="简介:" prop="stitle">
                <el-input
                  placeholder="请输入简介"
                  autocomplete="off"
                  v-model="news.stitle"
                ></el-input>
              </el-form-item>
            </Col>
            <Col v-bind="grid">
              <el-form-item label="分类:">
                <el-select
                  v-model="news.cate_id"
                  placeholder="分类"
                  style="width: 100%"
                  :rules="[{ required: true, message: '请选择分类' }]"
                >
                  <el-option
                    :label="item.html + item.title"
                    :value="item.id"
                    :key="item.id"
                    v-for="item in cateAr"
                  ></el-option>
                </el-select>
              </el-form-item>
            </Col>
            <Col v-bind="grid">
              <el-form-item label="封面图:">
                <ui-upload-much
                  :upUrl="upUrl"
                  :img-ar="news.imgAr"
                  :headers="upHeaders"
                  @onUpload="onUpload"
                  @onRemove="upRemove"
                ></ui-upload-much>
              </el-form-item>
            </Col>
            <Col v-bind="grid">
              <el-form-item label="内容:">
                <vue-ueditor-wrap
                  v-model="news.content"
                  @beforeInit="addCustomDialog"
                  :config="myConfig"
                  style="width: 95%"
                ></vue-ueditor-wrap>
              </el-form-item>
            </Col>
            <Col v-bind="grid">
              <el-form-item label="显示:" style="margin-bottom: 0">
                <el-radio-group v-model="news.is_show">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </Col>
            <Col v-bind="grid">
              <div style="margin-top: 10px"></div>
              <el-form-item>
                <el-button type="primary" @click="formSub">提交数据</el-button>
              </el-form-item>
            </Col>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </Card>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import VueUeditorWrap from 'vue-ueditor-wrap'
import IPageHeader from '../../../layouts/system/page-header/index'
import UiUploadMuch from '@/ui/upload/more_index'
import util from '../../../libs/util'
import {
  SystemNewsCateTree,
  SystemNewsSave,
  SystemNewsItem,
} from '../../../api/system/news'
import Setting from '../../../setting'
export default {
  name: 'news_add',
  components: {
    IPageHeader,
    UiUploadMuch,
    VueUeditorWrap,
  },
  computed: {
    ...mapState('system/page', ['opened', 'current']),
  },
  data() {
    return {
      upUrl: '',
      upHeaders: {},
      // 搜索区域
      grid: {
        xl: 24,
        lg: 24,
        md: 24,
        sm: 24,
        xs: 24,
      },
      news: {
        id: 0,
        title: '',
        cate_id: 0,
        is_show: 1,
        stitle: '',
        is_tui: 0,
        is_hot: 0,
        img: '',
        imgAr: [],
        content: '',
      },
      cateAr: [],
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 200, // 初始容器高度
        initialFrameWidth: '100%', // 初始容器宽度
        UEDITOR_HOME_URL: Setting.apiBaseURL + '/UEditor/',
        serverUrl: '',
      },
    }
  },
  created() {
    var upHeaders = {}
    // 上传路径
    this.upUrl = Setting.apiBaseURL + '/systemv1/upload/index'
    // 上传header数据
    const token = util.cookies.get('system_token')
    if (token) {
      upHeaders['SYSTEM-ACC-TOKEN'] = token
    }
    this.upHeaders = upHeaders
  },
  mounted() {
    var id = this.$route.params.id || 0
    var PromiseAr = []
    // tree
    PromiseAr.push(SystemNewsCateTree())
    if (id > 0) {
      PromiseAr.push(SystemNewsItem({ id: id }))
    }
    let loading = this.$loading('获取数据中...')
    Promise.all(PromiseAr)
      .then((res) => {
        loading.close()
        this.cateAr = [{ id: 0, title: '-选择分类-', html: '' }].concat(
          res[0].data
        )
        if (id > 0) {
          var data = res[1].data
          var imgAr = res[1].data.img.split(',')
          data.imgAr = imgAr
          this.news = data
        }
      })
      .catch((err) => {
        console.log(err)
        loading.close()
        this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
      })
  },
  methods: {
    ...mapActions('system/page', ['close']),
    addCustomDialog: function (editorId) {
      window.UE.registerUI(
        'test-dialog',
        function (editor, uiName) {
          // 创建 dialog
          let dialog = new window.UE.ui.Dialog({
            iframeUrl: '/system/widget/images/index.html?fodder=dialog',
            editor: editor,
            name: uiName,
            title: '上传图片',
            cssRules: 'width:600px;height:500px;padding:20px;',
          })
          this.dialog = dialog
          let btn = new window.UE.ui.Button({
            name: 'dialog-button',
            title: '上传图片',
            cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function () {
              // 渲染dialog
              dialog.render()
              dialog.open()
            },
          })
          return btn
        },
        37
      )
    },
    /**
     * 修改数据
     */
    formSub: function () {
      this.$refs['news'].validate((valid) => {
        if (valid) {
          let loading = this.$loading('提交数据中...')
          SystemNewsSave(this.news)
            .then((res) => {
              loading.close()
              if (res.code == 200) {
                this.$Message.success(res.msg)
                this.close({ tagName: this.current })
              } else {
                this.$alert(res.msg, '系统提示')
              }
            })
            .catch((err) => {
              console.log(err)
              loading.close()
              this.$alert('网络繁忙，加载失败，请稍等片刻在尝试!', '系统提示')
            })
        } else {
          this.$Message.error('请完成信息!')
        }
      })
    },
    /**
     * 上传文件
     * @param res
     */
    onUpload: function (res) {
      if (res.code == -1) {
        Notice.error({ title: '系统提示', content: res.msg })
      } else {
        this.news.imgAr.push(res.data.img)
      }
    },
    /**
     * 删除图片
     * @param index
     */
    upRemove: function (index) {
      this.news.imgAr.splice(index, 1)
      // this.$delete(this.formValidate,"imgAr",index);
    },
  },
}
</script>
